<template>
  <span class="m-icon" v-if="name" :style="style" :class="type">
    <template v-if="iconName.type === 'img'">
      <img v-if="iconName.type === 'img' && lazy" v-lazy='iconName.name'/>
      <img v-else :src='iconName.name'/>
    </template>
    <span
      class="m-icon-name-type"
      :style="{fontSize: size / 1.3 + 'px', color: simpleUtils.randomColor()}"
      v-if="iconName.type === 'name'">{{ iconName.name }}</span>
    <span
      v-if="iconName.type === 'font'"
      :style="{fontSize: size / 1.3 + 'px'}"
      class="iconfont"
      :class="'icon-' + iconName.name"></span>
    <svg
      v-if="iconName.type === 'symbol'"
      class="m-symbol-icon"
      aria-hidden="true">
      <use :xlink:href="'#icon-' + iconName.name"></use>
    </svg>
  </span>
</template>

<script>

export default {
  name: "MIcon",
  props: {
    /**
     * 开启懒加载（图片类型）
     */
    lazy: Boolean,
    /**
     * 图标名称
     */
    name: String,
    /**
     * 图标大小
     */
    size: {
      type: [String, Number],
      default: 20
    },
    /**
     * y轴偏移
     */
    tranY: {
      type: [String, Number],
      default: 2
    },
    /**
     * 颜色
     */
    color: String,
    /**
     * 类型，可选 primary|info|success|warning|error
     */
    type: String
  },
  computed: {
    iconName() {
      const realName = this.realName();
      if (realName.type === 'img') {
        realName.name = this.imgIconMap[realName.name];
      } else if (!realName.type) {
        realName.type = 'symbol';
      }
      return realName;
    },
    style() {
      let size = this.size.toString().replace("px", "").trim() + "px";
      let tranY = this.tranY.toString().replace("px", "").trim() + "px";
      return {
        width: size,
        height: size,
        transform: `translateY(${tranY})`,
        color: this.color
      }
    }
  },
  methods: {
    realName() {
      if (!this.name) return null;
      let type;
      const name = this.name.replace(/^\[.*.]/, (target, index, string) => {
        type = target.replace(/\[|]/g, "");
        return "";
      })
      return {
        name: name,
        type: type
      }
    }
  },
  created() {
    this.realName()
  }
}
</script>

<style lang="scss" scoped>
.m-icon {
  display: inline-block;

  &.primary {
    color: #2d8cf0;
  }

  &.info {
    color: #2db7f5;
  }

  &.success {
    color: #19be6b;
  }

  &.warning {
    color: #ff9900;
  }

  &.error {
    color: #ed4014;
  }

  .m-icon-name-type {
    font-weight: bold;
  }

  img {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }

  .m-symbol-icon {
    width: 100%;
    height: 100%;
  }
}
</style>
